from django_redis import get_redis_connection
from rest_framework import serializers
import re

from users.models import User, Address
from mall import settings
from goods.models import SKU


class RegisterCreateSerializer(serializers.ModelSerializer):
    # 由于模型类中没有这些字段，在继承ModelSerializer的时候需要额外增加
    # allow_null=False 不能为None
    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False, allow_blank=False,
                                     write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)

    class Meta:
        model = User
        fields = ['username', 'password', 'mobile', 'password2', 'sms_code', 'allow']
        # 需要保存到数据库的字段的选项不满足我们的要求，我们需要增加字段选项
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}', value):
            raise serializers.ValidationError("手机号格式不正确")
        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError("没有同意协议")
        return value

    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']
        if password != password2:
            raise serializers.ValidationError("密码不一致")
        sms_code = attrs['sms_code']
        mobile = attrs['mobile']
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code is None:
            raise serializers.ValidationError("验证码已过期")
        if sms_code != redis_code.decode():
            raise serializers.ValidationError("验证码输入错误")
        return attrs

    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        user = super(RegisterCreateSerializer, self).create(validated_data)
        user.set_password(validated_data['password'])
        user.save()

        from rest_framework_jwt.settings import api_settings
        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data.get('email')
        instance.email = email
        instance.save()
        # 在这里发送激活邮件
        url = instance.generic_verify_url()
        from celery_tasks.email.tasks import send_verify_mail
        send_verify_mail.delay(email, url)
        return instance


class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'create_time', 'update_time')

    def create(self, validated_data):
        # Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """

    class Meta:
        model = Address
        fields = ('title',)


class UserHistorySerializer(serializers.Serializer):
    sku_id = serializers.CharField(label='商品id', required=True)

    # 需要验证传过来的sku_id对应的商品是否存在
    def validated_sku_id(self, value):
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        return value

    def create(self, validated_data):
        redis_conn = get_redis_connection('history')
        # 考虑到浏览记录不能重复，并且后浏览的数据需要保存在前面
        # 查询到该数据先从数据库中删除，再添加
        # 为了区分该数据属于哪个用户，存储时在前面加上用户ID
        sku_id = validated_data.get('sku_id')
        user = self.context['request'].user
        redis_conn.lrem('history_%s' % user.id, 0, sku_id)
        redis_conn.lpush('history_%s' % user.id,sku_id)
        # 只保留5条数据，用ltrim
        redis_conn.ltrim('history_%s' % user.id,0,4)
        return validated_data

class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')